package com.ninong.ker.common.oss.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PartETag;
import com.aliyun.oss.model.UploadPartRequest;
import com.aliyun.oss.model.UploadPartResult;

/**
 * part上次工具类
 * @author 鸠摩智
 *
 */
public class PartUploader implements Runnable {

	private File localFile;
	private long startPos;

	private long partSize;
	private int partNumber;
	private String uploadId;
	private String bucketName;
	private String key;
	private OSSClient client;
	private List<PartETag> partTags;

	public PartUploader(File localFile, long startPos, long partSize, int partNumber, String uploadId,
			String bucketName, String key, OSSClient client,List<PartETag> partTags) {
		this.localFile = localFile;
		this.startPos = startPos;
		this.partSize = partSize;
		this.partNumber = partNumber;
		this.uploadId = uploadId;
		this.bucketName = bucketName;
		this.key = key;
		this.client = client;
		this.partTags = partTags;
	}

	@Override
	public void run() {
		InputStream instream = null;
		try {
			instream = new FileInputStream(this.localFile);
			instream.skip(this.startPos);

			UploadPartRequest uploadPartRequest = new UploadPartRequest();
			uploadPartRequest.setBucketName(bucketName);
			uploadPartRequest.setKey(key);
			uploadPartRequest.setUploadId(this.uploadId);
			uploadPartRequest.setInputStream(instream);
			uploadPartRequest.setPartSize(this.partSize);
			uploadPartRequest.setPartNumber(this.partNumber);

			UploadPartResult uploadPartResult = client.uploadPart(uploadPartRequest);
			System.out.println("Part#" + this.partNumber + " done\n");
			synchronized (partTags) {
				partTags.add(uploadPartResult.getPartETag());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (instream != null) {
				try {
					instream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
